#include "InSdkCheckNetStatus.h"

#define DEF_TAG                 "CheckNet"

typedef struct
{
    Com_s8 host[32];
    struct in_addr addr;
    Com_s32 port;
}SComNetStatusHostInfo,*pSComNetStatusHostInfo;

Com_u8 g_InSdkNetStatus_Connect_Flag = DEF_COM_FALSE;
Com_u8 g_InSdkNetStatus_Connect_8_8_8_8_Flag = DEF_COM_FALSE;
SComNetStatusHostInfo g_InSdkNetStatus_Host_Info = {{0}};

Com_s32 InSdkNetStatus_Connect_Server_Result(char *server,int server_port)
{
    if(g_InSdkNetStatus_Host_Info.port == 0)
    {
        struct hostent *host;
        host = gethostbyname(server);
        if((host == NULL) || (host->h_addr_list[0] == NULL))
        {
            res_init();
            return -1;
        }

        strncpy(g_InSdkNetStatus_Host_Info.host,server,sizeof(g_InSdkNetStatus_Host_Info.host));
        g_InSdkNetStatus_Host_Info.port = server_port;
        g_InSdkNetStatus_Host_Info.addr = *(struct in_addr *)(host->h_addr_list[0]);
        res_init();
    }

    int i,ret = 0;
    int skt;
    struct sockaddr_in sa;

    memset(&sa,0,sizeof(sa));

    sa.sin_addr = g_InSdkNetStatus_Host_Info.addr;
    sa.sin_port = htons(g_InSdkNetStatus_Host_Info.port);
    sa.sin_family = AF_INET;

    if((skt = (int)socket(AF_INET, SOCK_STREAM, 0)) >= 0)
    {
        for (i = 0; i < 2; i++)
        {
            if(connect(skt, (struct sockaddr *)&sa, sizeof(struct sockaddr_in)) == 0)
            {
                break;
            }
        }
        if (i == 2)
        {
            ret = -1;
        }

        close(skt);
    }
    else
    {
        return -1;
    }

    return ret;
}

Com_s32 Ext_InSdkNetStatus_Check(void)
{
    if(g_InSdkNetStatus_Connect_Flag == DEF_COM_TRUE)
    {
        return -1;
    }
    g_InSdkNetStatus_Connect_Flag = DEF_COM_TRUE;

    Com_s32 ret = -1;
    Com_s8 buf[20] = "www.baidu.com";

    ret = InSdkNetStatus_Connect_Server_Result(buf,80);
    g_InSdkNetStatus_Connect_Flag = DEF_COM_FALSE;
    return ret;
}

Com_s32 Ext_InSdkNetStatus_Check_8_8_8_8(Com_void)
{
    if(g_InSdkNetStatus_Connect_8_8_8_8_Flag == DEF_COM_TRUE)
    {
        return -1;
    }
    g_InSdkNetStatus_Connect_8_8_8_8_Flag = DEF_COM_TRUE;

    int ret = 0;
    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("8.8.8.8");
    server.sin_port = htons(53);

    int status = connect(sock, (struct sockaddr *)&server, sizeof(server));
    if(status == 0)
    {
        PRT_INFO(DEF_TAG,"Network is connected\n");
    }
    else
    {
        ret = -1;
        //PRT_WARN(DEF_TAG,"Network is disconnected.\n");
    }
    close(sock);
    g_InSdkNetStatus_Connect_8_8_8_8_Flag = DEF_COM_FALSE;

    return ret;
}
